package filtro;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class filtroLogin implements Filter {

	public filtroLogin() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
		res.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");

		PrintWriter out = res.getWriter();
		
		res.setContentType("text/html;charset=UTF-8");

		Integer sessao = (Integer) req.getSession().getAttribute("id");
		Integer funcao = (Integer) req.getSession().getAttribute("idfuncao");

		String url = req.getRequestURL().toString();

		if (sessao == null && !url.contains("login")) {
			if(!url.contains("ajax")){			
				res.sendRedirect("login.jsp");
			}else{
//				throw new RuntimeException("sessaoExpirou");
				out.print("sessaoExpirou");
			}
		} else {

			if (sessao != null && funcao > 1 && !url.contains("logoutServlet") && !url.contains("loginServlet") && funcao != 6) {
				if (!url.contains("osEnviada.jsp")) {
					if (!url.contains("ajax") && !url.contains("Servlet")) {
						res.sendRedirect("osEnviada.jsp");
					}
				}
//				if (funcao == 3 && !url.contains("impressor.jsp")) {
//					if (!url.contains("ajax")) {
//						res.sendRedirect("impressor.jsp");
//					}
//				}
//				if (funcao == 4 && !url.contains("producao.jsp")) {
//					if (!url.contains("ajax")) {
//						res.sendRedirect("producao.jsp");
//					}
//				}
//				if (funcao == 5 && !url.contains("entregador.jsp")) {
//					if (!url.contains("ajax") && !url.contains("finalizarOsServlet")) {
//						res.sendRedirect("entregador.jsp");
//					}
//				}
			}

			chain.doFilter(request, response);

		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
